package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.*;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.controller.app.PushController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.ListUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;

@Controller(value = "appMQuestionController")
@RequestMapping(value = "/app/m/question")
public class QuestionController extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "questionServiceImpl")
    private QuestionService questionService;
    @Resource(name = "snServiceImpl")
    private SnService snService;
    @Resource(name = "yiYuanTradeServiceImpl")
    private YiYuanTradeService yiYuanTradeService;
    @Resource(name = "reviewServiceImpl")
    private ReviewService reviewService;
    @Resource(name = "messageServiceImpl")
    private MessageService messageService;
    @Resource(name = "financialRecordServiceImpl")
    private FinancialRecordService financialRecordService;


    /**
     * 提问（android）
     * @param question
     * @param teacherId
     * @return
     */
    @RequestMapping(value = "/ask", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage ask(Question question, Long teacherId, String[] imageURL) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if(imageURL != null && imageURL.length > 0) {
                List<String> imageList = Arrays.asList(imageURL);
                question.setImages(imageList);
            }
            question.setMember(member);
            question.setAnswerStatus(Question.AnswerStatus.no);
            Member teacher = memberService.find(teacherId);
            if (teacher == null) {
                return JsonMessage.error("不存在该老师");
            }
            question.setTeacher(teacher);
            if (question.getPayPrice().compareTo(BigDecimal.ZERO) == 0) {
                //TODO 免费问题，默认已支付
                question.setPaymentStatus(Question.PaymentStatus.paid);
                //TODO 向老师发送通知
                String information = member.getName()+Constant.QUESTION_NOTICE;
//                PushController.noticeTest(teacher, information, question.getId(), Constant.GETUI_QUESTION);
                PushController.notice(teacher, information);
                //TODO 保存消息
                messageService.generateMessage(member, teacher, information);

            } else {
                question.setPaymentStatus(Question.PaymentStatus.unpaid);
            }
            question.setSn(snService.generate(Sn.Type.payment));
            questionService.save(question);
            return JsonMessage.success(
                    "sn", question.getSn(),
                    "title", question.getTitle(),
                    "price", question.getPayPrice()
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 提问（ios）
     * @param question
     * @param teacherId
     * @return
     */
    @RequestMapping(value = "/ask_ios", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage ask_ios(Question question, Long teacherId, String imageURL) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (!isValid(question)) {
                return JsonMessage.UNKNOWN_ERROR;
            }
            if(imageURL != null && !imageURL.isEmpty()) {
                List<String> imageList = ListUtils.string2List(imageURL);
                question.setImages(imageList);
            }
            question.setMember(member);
            question.setAnswerStatus(Question.AnswerStatus.no);
            Member teacher = memberService.find(teacherId);
            if (teacher == null) {
                return JsonMessage.error("不存在该老师");
            }
            question.setTeacher(teacher);
            if (question.getPayPrice().compareTo(BigDecimal.ZERO) == 0) {
                //TODO 免费问题，默认已支付
                question.setPaymentStatus(Question.PaymentStatus.paid);
                //TODO 向老师发送通知
                String information = member.getName()+Constant.QUESTION_NOTICE;
//                PushController.noticeTest(teacher, information, question.getId(), Constant.GETUI_QUESTION);
                PushController.notice(teacher, information);
                //TODO 保存消息
                messageService.generateMessage(member, teacher, information);
            } else {
                question.setPaymentStatus(Question.PaymentStatus.unpaid);
            }
            question.setSn(snService.generate(Sn.Type.payment));
            questionService.save(question);
            return JsonMessage.success(
                    "sn", question.getSn(),
                    "title", question.getTitle(),
                    "price", question.getPayPrice()
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 回答
     * @param id
     * @param answerContent
     * @return
     */
    @RequestMapping(value = "/answer", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage answer(Long id, String answerContent, String mediaURL, String timeLength) {
        try {
            Question question = questionService.find(id);
            Member teacher = memberService.getCurrentByToken();
            if (teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (answerContent != null && !"".equals(answerContent)) {
                question.setAnswerContent(answerContent);
            }
            if (mediaURL != null && !"".equals(mediaURL)) {
                question.setMediaURL(mediaURL);
            }
            if (timeLength != null && !"".equals(timeLength)) {
                question.setTimeLength(timeLength);
            }
            question.setAnswerStatus(Question.AnswerStatus.yes);
            questionService.update(question);
            //TODO 向用户发送通知
            String information = teacher.getName()+Constant.ANSWER_NOTICE;
//            PushController.noticeTest(teacher, information, question.getId(), Constant.GETUI_ANSWER);
            PushController.notice(question.getMember(), information);
            //TODO 保存消息
            messageService.generateMessage(teacher, question.getMember(), information);

            //TODO 生成老师收入记录
            teacher.setBalance(teacher.getBalance().add(question.getPayPrice()));
            //我的收入
            teacher.setEarnings(teacher.getEarnings().add(question.getPayPrice()));
            memberService.update(teacher);
            //老师收入记录
            financialRecordService.incomeRecordQuestion(question, null);

            return JsonMessage.success("回答已经提交");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 我的易问(已支付)
     * @return
     */
    @RequestMapping(value = "/myQuestions", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage myQuestions(Pageable pageable) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Page<Question> page = questionService.findQuestionPage(pageable, member);
            return JsonMessage.success(

                    "totalPage", page.getTotalPages(),

                    "pageNumber", page.getPageNumber(),

                    "pageSize", page.getPageSize(),

                    "total", page.getTotal(),

                    "content", JsonMessage.optimiseObj(
                            page.getContent(),
                            "title", "answerContent", "content", "id", "createDateF", "mediaURL", "teacher.avator", "answerStatus", "images", "timeLength",
                            "member.username", "name", "member.name", "payPrice", "payType", "birthDay", "birthHour", "gender", "email"
                    )
            );

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 查看问题
     * @param questionId
     * @return
     */
    @RequestMapping(value = "/showAnswer", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage showAnswer(Long questionId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Question question = questionService.find(questionId);
            if(question != null) {
                return JsonMessage.success(JsonMessage.optimiseObj(question, "answerContent", "id", "title", "mediaURL", "createDate", "teacher.avator", "content","images"));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 查看详情
     * @param questionId
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage detail(Long questionId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Question question = questionService.find(questionId);
            if(question == null) {
                return JsonMessage.error("找不到该问题");
            }
            return JsonMessage.success(JsonMessage.optimiseObj(question,"id", "title", "content", "images"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 老师-我的易答-易问
     * @return
     */
    @RequestMapping(value = "/questions", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage questions(Pageable pageable) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Page<Question> questionPage = questionService.findQuestionByTeacher(pageable, teacher, Question.PaymentStatus.paid, Question.AnswerStatus.no);

            return JsonMessage.success(

                    "totalPage", questionPage.getTotalPages(),

                    "pageNumber", questionPage.getPageNumber(),

                    "pageSize", questionPage.getPageSize(),

                    "total", questionPage.getTotal(),

                    "content", JsonMessage.optimiseObj(
                            questionPage.getContent(),
                            "title", "content", "id", "createDateF", "images", "member.avator",
                            "member.username", "name", "member.name", "payPrice", "payType", "birthDay", "birthHour", "gender", "email"
                    )
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 老师-我的易答-易答
     * @return
     */
    @RequestMapping(value = "/answers", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage answers(Pageable pageable) {
        try {
            Member teacher = memberService.getCurrentByToken();
            if(teacher == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Page<Question> answerPage = questionService.findQuestionByTeacher(pageable, teacher, Question.PaymentStatus.paid, Question.AnswerStatus.yes);

            return JsonMessage.success(
                    "totalPage", answerPage.getTotalPages(),
                    "pageNumber", answerPage.getPageNumber(),
                    "pageSize", answerPage.getPageSize(),
                    "total", answerPage.getTotal(),
                    "content", JsonMessage.optimiseObj(
                            answerPage.getContent(),
                            "title", "content", "answerContent", "id", "createDateF", "member.avator", "mediaURL", "images", "timeLength",
                            "member.username", "name", "member.name", "payPrice", "payType", "birthDay", "birthHour", "gender", "email"
                            ));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 判断用户是否已经购买
     * @param questionId
     * @return
     */
    @RequestMapping(value = "/isPay", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage isPay(Long questionId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Question question = questionService.find(questionId);

            boolean isPay;
            if(question.getTeacher().getId().equals(member.getId())) {
                isPay = true;
            } else if(question.getMember().getId().equals(member.getId()) && Question.PaymentStatus.paid.equals(question.getPaymentStatus())) {
                isPay = true;
            } else {
                isPay = yiYuanTradeService.isPay(member, questionId) > 0 ? true : false;
            }
            return JsonMessage.success("isPay", isPay);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 易问（老师详情）
     */
    @RequestMapping(value = "/teacher_detail", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage teacherDetail(Long teacherId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Member teacher = memberService.find(teacherId);
            if(teacher == null) {
                return JsonMessage.error("找不到该老师");
            }
            //获取我的回答数
            long answers = questionService.myAnswerCounts(teacher);

            //获取我的评价
            long reviews = reviewService.myReviews(teacher);

            MemberCertification memberCertification = teacher.getMemberCertification();
            //获取综合评价
            NumberFormat formatter = new DecimalFormat("0.00%");
            double serviceScore = reviewService.serviceScore(teacher);
            double schemeScore = reviewService.schemeScore(teacher);
            double feedbackScore = reviewService.feedbackScore(teacher);
            double avg = (serviceScore+schemeScore+feedbackScore)/3*2;
            String note = "";
            if (avg >= 6) {
                note = "好评";
            } else if (avg >= 3 && avg < 6) {
                note = "中评";
            } else if (avg > 0 && avg < 3 ){
                note = "差评";
            } else {
                note = "好评";
            }
            avg = avg / 10;
            String percent = formatter.format(avg);
            if (avg == 0) {
                percent = "100.00%";
            }
            return JsonMessage.success(
                    "answers", answers,
                    "reviews", reviews,
                    "percent", percent+note,
                    "memberCertification",
                    JsonMessage.optimiseObj(memberCertification,
                    "payFengshui", "payGanqing","payShiye","payOther"),
                    "teacher", JsonMessage.optimiseObj(teacher, "avator", "name", "introduction"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 易问易答列表（按老师id）
     * @param pageable
     * @param teacherId
     * @return
     */
    @RequestMapping(value = "/questionList", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage questionList(Pageable pageable, Long teacherId) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Member teacher = memberService.find(teacherId);
            if(teacher == null) {
                return JsonMessage.error("找不到该老师");
            }
            Page<Question> questionPage = questionService.findQuestionByTeacher(pageable, teacher, Question.PaymentStatus.paid, Question.AnswerStatus.yes);
            return JsonMessage.success(
                    "totalPage", questionPage.getTotalPages(),
                    "pageNumber", questionPage.getPageNumber(),
                    "pageSize", questionPage.getPageSize(),
                    "total", questionPage.getTotal(),
                    "content", JsonMessage.optimiseObj(
                            questionPage.getContent(),
                            "title", "answerContent", "id", "createDate", "mediaURL", "images", "timeLength"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
